<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="renderer" content="webkit">
    <title>老年体检数据统计看板</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/all.min.css">
    <script src="css/chart.js"></script>
    <style>
        :root {
            --primary-color: #4CAF50; /* 草绿色主色调 */
            --secondary-color: #81C784; /* 浅草绿 */
            --accent-color: #C8E6C9; /* 淡草绿 */
            --dark-color: #388E3C; /* 深草绿 */
            --light-bg: #E8F5E9; /* 非常淡的草绿背景 */
            --card-bg: #FFFFFF;
            --text-dark: #2E7D32; /* 深绿色文字 */
            --text-light: #FFFFFF;
            --text-bright: #1B5E20; /* 更亮的文字颜色 */
            --text-highlight: #FF5722; /* 高亮文字颜色 */
            --success-color: #2E7D32; /* 深绿色表示成功 */
            --warning-color: #F57F17; /* 橙色警告 */
            --danger-color: #C62828; /* 红色危险 */
            --info-color: #00695C; /* 深蓝绿色信息色 */
        }
        
        body {
            background: linear-gradient(135deg, #C8E6C9 0%, #81C784 50%, #4CAF50 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding-top: 20px;
            color: var(--text-dark);
            min-height: 100vh;
        }
        
        .container {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(76, 175, 80, 0.2);
            padding: 25px;
            margin-bottom: 30px;
        }
        
        .header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: var(--text-light);
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 8px 20px rgba(76, 175, 80, 0.3);
            text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
        }
        
        .header h1 {
            color: #FFFFFF;
            font-weight: 800;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .card {
            border-radius: 15px;
            box-shadow: 0 6px 15px rgba(76, 175, 80, 0.15);
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 25px;
            border: none;
            background-color: var(--card-bg);
            height: 100%;
        }
        
        .card:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 25px rgba(76, 175, 80, 0.2);
        }
        
        .card-header {
            background: linear-gradient(to right, var(--secondary-color), var(--primary-color));
            color: var(--text-light);
            border-bottom: none;
            font-weight: 700;
            padding: 15px 20px;
            border-radius: 15px 15px 0 0 !important;
        }
        
        .stat-card {
            text-align: center;
            padding: 12px 12px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            height: 100%;
        }
        
        .stat-card h2 {
            font-weight: 800;
            font-size: 2.2rem;
            margin: 10px 0;
            color: var(--info-color);
        }
        
        .stat-card .card-title {
            font-size: 1rem;
            color: var(--text-dark);
            font-weight: 700;
        }
        
        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            margin: 5px 0;
            color: var(--text-bright);
        }
        
        .badge {
            font-weight: 600;
            padding: 6px 12px;
            border-radius: 20px;
            background-color: rgba(255, 255, 255, 0.8) !important;
            color: var(--dark-color) !important;
            border: 1px solid rgba(56, 142, 60, 0.3);
        }
        
        .progress {
            height: 10px;
            margin-top: 8px;
            border-radius: 10px;
            background-color: #e9ecef;
        }
        
        .progress-bar {
            border-radius: 10px;
        }
        
        .analysis-container {
            background-color: var(--light-bg);
            border-radius: 15px;
            padding: 20px;
            margin-top: 20px;
            box-shadow: 0 4px 10px rgba(76, 175, 80, 0.1);
        }
        
        .analysis-container h4 {
            color: var(--dark-color);
            font-weight: 700;
            border-bottom: 2px solid var(--secondary-color);
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        
        .analysis-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px dashed #C8E6C9;
        }
        
        .analysis-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        
        .analysis-title {
            font-weight: 700;
            color: var(--dark-color);
            margin-bottom: 5px;
            font-size: 1.1rem;
        }
        
        .analysis-content {
            color: var(--text-dark);
            font-size: 1rem;
            line-height: 1.5;
        }
        
        .chart-container {
            height: 350px;
            position: relative;
            margin-bottom: 25px;
        }
        
        .bar-chart-container {
            height: 500px;
            position: relative;
        }
        
        .table-container {
            overflow-x: auto;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(76, 175, 80, 0.1);
            background-color: white;
            margin-top: 20px;
        }
        
        .table thead th {
            background: linear-gradient(to right, var(--secondary-color), var(--primary-color));
            color: var(--text-light);
            position: sticky;
            top: 0;
            vertical-align: middle;
            font-weight: 600;
            padding: 12px 15px;
            font-size: 1rem;
        }
        
        .table tbody td {
            padding: 12px 15px;
            vertical-align: middle;
            color: #2E7D32;
            font-weight: 500;
        }
        
        .table tfoot td {
            padding: 12px 15px;
            vertical-align: middle;
            font-weight: 700;
            background-color: rgba(129, 199, 132, 0.1);
            color: var(--dark-color);
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(200, 230, 201, 0.3);
        }
        
        .rate-high {
            color: var(--success-color);
            font-weight: 700;
        }
        
        .rate-medium {
            color: var(--warning-color);
            font-weight: 700;
        }
        
        .rate-low {
            color: var(--danger-color);
            font-weight: 700;
        }
        
        .table-striped tbody tr:nth-of-type(odd) {
            background-color: rgba(232, 245, 233, 0.3);
        }
        
        .table-striped tbody tr:nth-of-type(even) {
            background-color: rgba(255, 255, 255, 0.8);
        }
        
        .filter-section {
            background-color: var(--light-bg);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 4px 10px rgba(76, 175, 80, 0.1);
        }
        
        .btn-custom {
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            color: white;
            border: none;
            font-weight: 600;
            border-radius: 10px;
            padding: 10px 20px;
        }
        
        .btn-custom:hover {
            background: linear-gradient(to right, var(--secondary-color), var(--primary-color));
            color: white;
            box-shadow: 0 4px 10px rgba(76, 175, 80, 0.2);
        }

        .stat-card .card-title {
            color: var(--dark-color);
            font-weight: 700;
            font-size: 1.1rem;
        }

        .stat-card .stat-value {
            color: var(--text-bright);
            font-weight: 800;
            font-size: 2.2rem;
        }
        
        footer {
            margin-top: 40px;
            padding: 20px 0;
            color: var(--text-dark);
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        /* 修改统计卡片背景色 */
        .col-md-3:nth-child(1) .card {
            background: linear-gradient(135deg, #E8F5E9 0%, #C8E6C9 100%);
            border-top: 4px solid #C8E6C9;
        }
        
        .col-md-3:nth-child(2) .card {
            background: linear-gradient(135deg, #E8F5E9 0%, #81C784 100%);
            border-top: 4px solid #81C784;
        }
        
        .col-md-3:nth-child(3) .card {
            background: linear-gradient(135deg, #E8F5E9 0%, #4CAF50 100%);
            border-top: 4px solid #4CAF50;
        }
        
        .col-md-3:nth-child(4) .card {
            background: linear-gradient(135deg, #E8F5E9 0%, #388E3C 100%);
            border-top: 4px solid #388E3C;
        }
        
        /* 将统计卡片标题改为h3 */
        .stat-card h3 {
            font-size: 1.2rem;
            color: var(--dark-color);
            font-weight: 700;
            margin-bottom: 15px;
        }
        
        /* 更新卡片内部文字样式 */
        .stat-card .card-title,
        .stat-card .stat-value,
        .stat-card span {
            color: var(--text-dark) !important;
            text-shadow: none;
        }
        
        /* 调整徽章样式 */
        .stat-card .badge {
            background-color: rgba(255,255,255,0.7) !important;
            color: var(--dark-color) !important;
            border: 1px solid rgba(56, 142, 60, 0.2);
            font-weight: 700;
        }
        
        /* 进度条样式优化 */
        .stat-card .progress {
            background-color: rgba(56, 142, 60, 0.1) !important;
            height: 12px;
            border-radius: 15px;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
        }
        
        /* 进度条颜色增强 */
        #totalStandardProgress.bg-info {
            background-color: var(--info-color) !important;
        }
        
        #score99Progress.bg-success {
            background-color: var(--success-color) !important;
        }
        
        #physicalIssuesProgress.bg-warning {
            background-color: var(--warning-color) !important;
        }
        
        #assessmentIssuesProgress.bg-danger {
            background-color: var(--danger-color) !important;
        }
        
        /* 卡片悬停效果增强 */
        .card:hover {
            box-shadow: 0 15px 30px rgba(76, 175, 80, 0.25);
            transform: translateY(-10px);
        }
        
        /* 卡片标题颜色调整 */
        .stat-card .card-title {
            color: var(--dark-color) !important;
            font-weight: 700;
        }
        
        .stat-card .stat-value {
            color: var(--text-bright) !important;
            font-weight: 800;
        }
        
        .issue-item {
            margin-bottom: 8px;
            padding: 8px 12px;
            background-color: rgba(255, 255, 255, 0.7);
            border-radius: 8px;
            border-left: 4px solid var(--warning-color);
            color: var(--text-dark);
            font-weight: 500;
        }
        
        /* 为表格中数值偏大的前3个数据添加更有层次的高亮效果 */
        .highlight-top {
            background: linear-gradient(to right, rgba(255, 215, 0, 0.3), rgba(255, 215, 0, 0.1)) !important;
            color: #2E7D32;
            font-weight: 700;
        }
        
        .highlight-1 {
            background: linear-gradient(to right, rgba(245, 127, 23, 0.25), rgba(245, 127, 23, 0.1)) !important;
            font-weight: 600;
            color: var(--text-dark);
        }
        
        .highlight-2 {
            background: linear-gradient(to right, rgba(255, 165, 0, 0.2), rgba(255, 165, 0, 0.08)) !important;
            font-weight: 600;
            color: var(--text-dark);
        }
        
        .highlight-3 {
            background: linear-gradient(to right, rgba(255, 185, 0, 0.15), rgba(255, 185, 0, 0.06)) !important;
            font-weight: 600;
            color: var(--text-dark);
        }
        
        /* 输入框和选择框样式 */
        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid var(--secondary-color);
            padding: 10px 15px;
            color: var(--text-dark);
            font-weight: 500;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(76, 175, 80, 0.25);
        }
        
        .input-group-text {
            background-color: var(--secondary-color);
            color: white;
            border: 2px solid var(--secondary-color);
            border-right: none;
        }
        
        /* 浏览器兼容性提示 */
        .browser-warning {
            display: none;
            background-color: #ff9800;
            color: white;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        
        .browser-warning h5 {
            margin-bottom: 10px;
            font-weight: 700;
        }
        
        .browser-warning ul {
            margin-bottom: 0;
            padding-left: 20px;
        }
        
        .chart-error {
            display: none;
            text-align: center;
            padding: 20px;
            background-color: #ffebee;
            border-radius: 10px;
            margin: 10px 0;
            color: #c62828;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .header {
                padding: 15px;
            }
            
            .stat-card h2 {
                font-size: 1.8rem;
            }
            
            .chart-container {
                height: 300px;
            }
            
            .bar-chart-container {
                height: 400px;
            }
            
            .table thead th {
                font-size: 0.9rem;
                padding: 8px 10px;
            }
            
            .table tbody td {
                padding: 8px 10px;
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
    <!-- 浏览器兼容性提示 -->
    <div class="container browser-warning" id="browserWarning">
        <h5><i class="fas fa-exclamation-triangle me-2"></i>浏览器兼容性提示</h5>
        <p>检测到您可能在使用兼容模式或旧版浏览器，这可能导致图表无法正常显示。</p>
        <p>建议您：</p>
        <ul>
            <li>切换360浏览器到<strong>极速模式</strong></li>
            <li>更新浏览器到最新版本</li>
            <li>使用Chrome、Firefox或Edge等现代浏览器</li>
        </ul>
    </div>

    <div class="container">
        <!-- 标题区域 -->
        <div class="header text-center">
            <h1><i class="fas fa-user-md me-2"></i>老年体检数据统计看板</h1>
            <p class="mb-0">各区域老年人体检情况与数据分析</p>
        </div>
        
        <!-- 筛选区域 -->
        <div class="filter-section">
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" id="searchInput" class="form-control" placeholder="搜索体检医院...">
                    </div>
                </div>
                <div class="col-md-3">
                    <select id="regionFilter" class="form-select">
                        <option value="">所有区域</option>
                        <!-- 区域选项将通过JS动态添加 -->
                    </select>
                </div>
                <div class="col-md-3">
                    <button id="resetFilters" class="btn btn-custom w-100">
                        <i class="fas fa-sync-alt me-1"></i>重置筛选
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 统计卡片 -->
        <div class="row">
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <h3 class="card-title">体检总人次</h3>
                        <h2 id="totalExamCount">0</h2>
                        <div class="mt-3">
                            <span class="badge bg-primary">规范数: <span id="totalStandardCount">0</span></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <h3 class="card-title">规范数</h3>
                        <h2 id="totalStandardValue">0</h2>
                        <div class="mt-2">
                            <span>总规范率: <span id="standardRate">0%</span></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <h3 class="card-title">总规范率</h3>
                        <div class="stat-value text-info" id="standardRateValue">0%</div>
                        <div class="mt-2">
                            <span>分值≥99人数: <span id="score99Count">0</span></span>
                        </div>
                        <div class="progress">
                            <div id="totalStandardProgress" class="progress-bar bg-info" role="progressbar" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <h3 class="card-title">总问题数</h3>
                        <div class="stat-value text-warning" id="totalIssuesValue">0</div>
                        <div class="mt-2">
                            <span>平均问题数: <span id="avgIssuesValue">0</span></span>
                        </div>
                        <div class="progress">
                            <div id="totalIssuesProgress" class="progress-bar bg-warning" role="progressbar" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 数据分析区域 -->
        <div class="analysis-container">
            <h4><i class="fas fa-chart-line me-2"></i>全部数据初步分析结果</h4>
            <div class="row mt-3">
                <div class="col-md-6">
                    <div class="analysis-item">
                        <div class="analysis-title">规范率分析</div>
                        <div class="analysis-content" id="standardRateAnalysis">加载中...</div>
                    </div>
                    <div class="analysis-item">
                        <div class="analysis-title">分值≥99比例分析</div>
                        <div class="analysis-content" id="score99Analysis">加载中...</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="analysis-item">
                        <div class="analysis-title">主要问题分布</div>
                        <div class="analysis-content" id="issuesAnalysis">加载中...</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 图表区域 -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-chart-bar me-2"></i>各区域体检人次与规范率对比
                    </div>
                    <div class="card-body">
                        <div class="chart-error" id="chartError1">
                            <i class="fas fa-exclamation-circle fa-2x mb-3"></i>
                            <p>图表加载失败，可能是浏览器兼容性问题</p>
                            <button class="btn btn-sm btn-outline-danger mt-2" onclick="renderCharts()">重试加载图表</button>
                        </div>
                        <div class="chart-container">
                            <canvas id="examChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-chart-bar me-2"></i>各单位详细数据分布
                    </div>
                    <div class="card-body">
                        <div class="chart-error" id="chartError2">
                            <i class="fas fa-exclamation-circle fa-2x mb-3"></i>
                            <p>图表加载失败，可能是浏览器兼容性问题</p>
                            <button class="btn btn-sm btn-outline-danger mt-2" onclick="renderCharts()">重试加载图表</button>
                        </div>
                        <div class="bar-chart-container">
                            <canvas id="detailsChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="card mt-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <i class="fas fa-table me-2"></i>详细数据
                </div>
                <div class="text-muted small">
                    共 <span id="totalCount">0</span> 条记录
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-container">
                    <table class="table table-hover table-striped mb-0">
                        <thead>
                            <tr>
                                <th class="sortable" data-sort="region">体检医院</th>
                                <th class="sortable" data-sort="examCount">体检总人次数</th>
                                <th class="sortable" data-sort="generalIssues">一般检查</th>
                                <th class="sortable" data-sort="elderlyAssessment">老年评估</th>
                                <th class="sortable" data-sort="lifestyleIssues">生活方式</th>
                                <th class="sortable" data-sort="physicalExamIssues">物理检查项</th>
                                <th class="sortable" data-sort="biochemicalExam">生化检查</th>
                                <th class="sortable" data-sort="instrumentExam">器械检查</th>
                                <th class="sortable" data-sort="existingHealthIssues">现存健康问题</th>
                                <th class="sortable" data-sort="healthAssessment">健康评价</th>
                                <th class="sortable" data-sort="healthGuidance">健康指导</th>
                                <th class="sortable" data-sort="riskFactorControl">危险因素控制</th>
                            </tr>
                        </thead>
                        <tbody id="dataBody">
                            <!-- 数据将通过JS动态填充 -->
                        </tbody>
                        <tfoot id="summaryRow">
                            <!-- 合计行将通过JS动态填充 -->
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- 页脚 -->
        <footer class="text-center">
            <p>数据更新时间: <span id="updateTime"></span></p>
            <p class="small">© 老年体检数据统计系统-郁进</p>
        </footer>
    </div>
    <script>
        // 全局变量
        let originalData = [
  {
    "体检医院": "万庄村委会",
    "体检总人次数": 729,
    "规范数": 721,
    "规范率": 0.989,
    "分值>=99": 721,
    "分值>=99比": 0.989,
    "无法核查": 0.0,
    "一般检查": 0,
    "老年评估": 0.0,
    "生活方式": 7,
    "物理检查项": 0,
    "生化检查": 0,
    "器械检查": 0.0,
    "现存健康问题": 0,
    "健康评价": 9,
    "健康指导": 0.0,
    "危险因素控制": 7
  },
  {
    "体检医院": "万杨村委会",
    "体检总人次数": 760,
    "规范数": 688,
    "规范率": 0.9053,
    "分值>=99": 688,
    "分值>=99比": 0.9053,
    "无法核查": 0.0,
    "一般检查": 3,
    "老年评估": 0.0,
    "生活方式": 3,
    "物理检查项": 9,
    "生化检查": 0,
    "器械检查": 0.0,
    "现存健康问题": 2,
    "健康评价": 69,
    "健康指导": 0.0,
    "危险因素控制": 11
  }
];
        let filteredData = [];
        let currentSort = { column: 'region', direction: 'asc' };
        let examChartInstance = null;
        let detailsChartInstance = null;
        let topIssues = [];

        // 检测浏览器兼容性
        function checkBrowserCompatibility() {
            const isIE = /*@cc_on!@*/false || !!document.documentMode;
            const isOldBrowser = !window.Promise || !window.Map || !window.Set;
            
            if (isIE || isOldBrowser) {
                document.getElementById('browserWarning').style.display = 'block';
                return false;
            }
            return true;
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 检查浏览器兼容性
            const isCompatible = checkBrowserCompatibility();
            
            // 设置更新时间
            document.getElementById('updateTime').textContent = new Date().toLocaleString();
            
            // 加载数据
            loadData();
            
            // 设置事件监听器
            document.getElementById('searchInput').addEventListener('input', filterData);
            document.getElementById('regionFilter').addEventListener('change', filterData);
            document.getElementById('resetFilters').addEventListener('click', resetFilters);
            
            // 设置表格排序
            document.querySelectorAll('.sortable').forEach(header => {
                header.addEventListener('click', function() {
                    sortTable(this.dataset.sort);
                });
            });
        });

        // 加载JSON数据
        function loadData() {
            try {
                filteredData = [...originalData];
                
                // 填充区域筛选器
                populateRegionFilter();
                
                // 更新统计数据
                updateStatistics();
                
                // 生成分析报告
                generateAnalysisReport();
                
                // 渲染表格 - 确保按原始region顺序
                renderTable();
                
                // 渲染图表 - 确保按原始region顺序
                renderCharts();
                
            } catch (error) {
                console.error('加载数据失败:', error);
                document.getElementById('dataBody').innerHTML = `
                    <tr>
                        <td colspan="12" class="text-center text-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>数据加载失败，请刷新页面重试
                        </td>
                    </tr>
                `;
            }
        }
        
        // 填充区域筛选器
        function populateRegionFilter() {
            const regionFilter = document.getElementById('regionFilter');
            const regions = [...new Set(originalData.map(item => item.体检医院))].sort();
            
            regions.forEach(region => {
                const option = document.createElement('option');
                option.value = region;
                option.textContent = region;
                regionFilter.appendChild(option);
            });
        }

        // 更新统计数据
        function updateStatistics() {
            // 计算总数
            const totalExamCount = filteredData.reduce((sum, item) => sum + item.体检总人次数, 0);
            const totalStandardCount = filteredData.reduce((sum, item) => sum + item.规范数, 0);
            const totalScore99Count = filteredData.reduce((sum, item) => sum + item['分值>=99'], 0);
            
            // 计算比率
            const totalStandardRate = totalStandardCount / totalExamCount;
            
            // 计算总问题数
            const totalIssues = filteredData.reduce((sum, item) => {
                return sum + item.一般检查 + item.老年评估 + item.生活方式 + item.物理检查项 + item.生化检查 + 
                    item.器械检查 + item.现存健康问题 + item.健康评价 + item.健康指导 + item.危险因素控制;
            }, 0);
            
            const avgIssues = totalIssues / totalExamCount;
            
            // 更新统计卡片
            document.getElementById('totalExamCount').textContent = totalExamCount.toLocaleString();
            document.getElementById('totalStandardCount').textContent = totalStandardCount.toLocaleString();
            document.getElementById('totalStandardValue').textContent = totalStandardCount.toLocaleString();
            document.getElementById('standardRate').textContent = (totalStandardRate * 100).toFixed(1) + '%';
            document.getElementById('standardRateValue').textContent = (totalStandardRate * 100).toFixed(1) + '%';
            document.getElementById('score99Count').textContent = totalScore99Count.toLocaleString();
            document.getElementById('totalIssuesValue').textContent = totalIssues.toLocaleString();
            document.getElementById('avgIssuesValue').textContent = avgIssues.toFixed(2);
            
            // 更新进度条
            document.getElementById('totalStandardProgress').style.width = (totalStandardRate * 100) + '%';
            document.getElementById('totalIssuesProgress').style.width = Math.min(totalIssues / 2000, 100) + '%';
            
            // 更新总记录数
            document.getElementById('totalCount').textContent = filteredData.length;
        }

        // 生成分析报告
        function generateAnalysisReport() {
            // 规范率分析- 显示前3名和后3名
            const standardRateData = originalData.map(item => ({
                region: item.体检医院,
                rate: item.规范率
            }));
            
            // 按规范率排序（从高到低）
            standardRateData.sort((a, b) => b.rate - a.rate);
            
            // 获取前3名和后3名
            const top3 = standardRateData.slice(0, 3);
            const bottom3 = standardRateData.slice(-3).reverse(); // 反向排序，从最差开始
            
            // 构建前3名显示字符串
            let top3Html = top3.map(item => 
                `<span class="rate-high">${item.region}(${(item.rate * 100).toFixed(1)}%)</span>`
            ).join('、');
            
            // 构建后3名显示字符串
            let bottom3Html = bottom3.map(item => 
                `<span class="rate-low">${item.region}(${(item.rate * 100).toFixed(1)}%)</span>`
            ).join('、');
            
            document.getElementById('standardRateAnalysis').innerHTML = `
                最佳: <br>${top3Html}<br>
                偏低:<br> ${bottom3Html}
            `;
            
            // 分值≥99比例分析
            const score99RateData = originalData.map(item => ({
                region: item.体检医院,
                rate: item['分值>=99比']
            }));
            
            // 按分值≥99比例排序（从高到低）
            score99RateData.sort((a, b) => b.rate - a.rate);
            
            // 获取前3名和后3名
            const top3Score = score99RateData.slice(0, 3);
            const bottom3Score = score99RateData.slice(-3).reverse();
            
            // 构建前3名显示字符串
            let top3ScoreHtml = top3Score.map(item => 
                `<span class="rate-high">${item.region}(${(item.rate * 100).toFixed(1)}%)</span>`
            ).join('、');
            
            // 构建后3名显示字符串
            let bottom3ScoreHtml = bottom3Score.map(item => 
                `<span class="rate-low">${item.region}(${(item.rate * 100).toFixed(1)}%)</span>`
            ).join('、');
            
            document.getElementById('score99Analysis').innerHTML = `
                最佳:<br> ${top3ScoreHtml}<br>
                偏低: <br>${bottom3ScoreHtml}
            `;
            
            // 主要问题分布分析
            const issuesData = {
                "一般检查": originalData.reduce((sum, item) => sum + item.一般检查, 0),
                "老年评估": originalData.reduce((sum, item) => sum + item.老年评估, 0),
                "生活方式": originalData.reduce((sum, item) => sum + item.生活方式, 0),
                "物理检查项": originalData.reduce((sum, item) => sum + item.物理检查项, 0),
                "器械检查": originalData.reduce((sum, item) => sum + item.器械检查, 0),
                "生化检查": originalData.reduce((sum, item) => sum + item.生化检查, 0),
                "现存健康问题": originalData.reduce((sum, item) => sum + item.现存健康问题, 0),
                "健康评价": originalData.reduce((sum, item) => sum + item.健康评价, 0),
                "健康指导": originalData.reduce((sum, item) => sum + item.健康指导, 0),
                "危险因素控制": originalData.reduce((sum, item) => sum + item.危险因素控制, 0)
            };
            
            // 找出问题最多的三项
            topIssues = Object.entries(issuesData)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 5);
            
            let issuesHtml = topIssues.map(([key, value]) => 
                `<div class="issue-item">${key}: <span class="rate-medium">${value}</span></div>`
            ).join('');
            
            document.getElementById('issuesAnalysis').innerHTML = issuesHtml;
        }

        // 渲染表格
        function renderTable() {
            const tbody = document.getElementById('dataBody');
            const tfoot = document.getElementById('summaryRow');
            tbody.innerHTML = '';
            
            if (filteredData.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="12" class="text-center text-muted">
                            <i class="fas fa-info-circle me-2"></i>没有找到匹配的数据
                        </td>
                    </tr>
                `;
                tfoot.innerHTML = '';
                return;
            }
            
            // 计算每个字段的最大值
            const maxValues = {};
            const fields = [
                '一般检查', '老年评估', '生活方式', '物理检查项', 
                '生化检查', '器械检查', '现存健康问题', '健康评价', 
                '健康指导', '危险因素控制'
            ];
            
            // 初始化最大值对象
            fields.forEach(field => {
                maxValues[field] = 0;
            });
            
            // 计算每个字段的最大值
            filteredData.forEach(item => {
                fields.forEach(field => {
                    const value = item[field];
                    if (value > maxValues[field]) {
                        maxValues[field] = value;
                    }
                });
            });
            
            // 计算每个字段的前三高值
            const topValues = {};
            fields.forEach(field => {
                const values = filteredData.map(item => item[field]).sort((a, b) => b - a);
                topValues[field] = values.slice(0, 3);
            });
            
            // 渲染数据行
            filteredData.forEach((item, index) => {
                const row = document.createElement('tr');
                
                // 添加主要列
                row.innerHTML = `
                    <td>${item.体检医院}</td>
                    <td>${item.体检总人次数}</td>
                `;
                
                // 添加问题字段列
                fields.forEach(field => {
                    const value = item[field];
                    let cellClass = '';
                    
                    // 检查是否为该字段的前三高值
                    if (topValues[field].includes(value)) {
                        const rank = topValues[field].indexOf(value) + 1;
                        cellClass = `highlight-${rank}`;
                    }
                    
                    row.innerHTML += `<td class="${cellClass}">${value}</td>`;
                });
                
                tbody.appendChild(row);
            });
            
            // 计算合计行
            const summaryRow = document.createElement('tr');
            summaryRow.classList.add('highlight-top');
            summaryRow.innerHTML = `<td><strong>合计</strong></td>`;
            
            // 计算体检总人次数合计
            const totalExamCount = filteredData.reduce((sum, item) => sum + item.体检总人次数, 0);
            summaryRow.innerHTML += `<td><strong>${totalExamCount.toLocaleString()}</strong></td>`;
            
            // 计算各问题字段合计
            fields.forEach(field => {
                const total = filteredData.reduce((sum, item) => sum + item[field], 0);
                summaryRow.innerHTML += `<td><strong>${total.toLocaleString()}</strong></td>`;
            });
            
            tfoot.innerHTML = summaryRow.outerHTML;
        }

        // 渲染图表
        function renderCharts() {
            // 隐藏错误提示
            document.getElementById('chartError1').style.display = 'none';
            document.getElementById('chartError2').style.display = 'none';
            
            try {
                // 销毁旧图表实例
                if (examChartInstance) examChartInstance.destroy();
                if (detailsChartInstance) detailsChartInstance.destroy();
                
                // 按原始region顺序排序数据
                const regionOrderMap = {};
                originalData.forEach((item, index) => {
                    regionOrderMap[item.体检医院] = index;
                });
                
                const sortedData = [...filteredData].sort((a, b) => {
                    const indexA = regionOrderMap[a.体检医院];
                    const indexB = regionOrderMap[b.体检医院];
                    return indexA - indexB;
                });
                
                // 体检人次与规范率对比图表
                const examCtx = document.getElementById('examChart').getContext('2d');
                const examLabels = sortedData.map(item => item.体检医院);
                
                examChartInstance = new Chart(examCtx, {
                    type: 'bar',
                    data: {
                        labels: examLabels,
                        datasets: [
                            {
                                label: '体检总人次数',
                                data: sortedData.map(item => item.体检总人次数),
                                backgroundColor: 'rgba(93, 140, 174, 0.7)',
                                borderColor: 'rgba(93, 140, 174, 1)',
                                borderWidth: 1,
                                yAxisID: 'y'
                            },
                            {
                                label: '规范率 (%)',
                                data: sortedData.map(item => item.规范率 * 100),
                                backgroundColor: 'rgba(88, 214, 141, 0.7)',
                                borderColor: 'rgba(88, 214, 141, 1)',
                                borderWidth: 1,
                                type: 'line',
                                yAxisID: 'y1'
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                type: 'linear',
                                display: true,
                                position: 'left',
                                title: {
                                    display: true,
                                    text: '体检人次数',
                                    font: {
                                        size: 16,
                                        weight: 'bold'
                                    }
                                },
                                ticks: {
                                    font: {
                                        size: 14
                                    }
                                }
                            },
                            y1: {
                                type: 'linear',
                                display: true,
                                position: 'right',
                                min: 0,
                                max: 100,
                                title: {
                                    display: true,
                                    text: '规范率 (%)',
                                    font: {
                                        size: 16,
                                        weight: 'bold'
                                    }
                                },
                                ticks: {
                                    font: {
                                        size: 14
                                    }
                                },
                                grid: {
                                    drawOnChartArea: false
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '体检医院',
                                    font: {
                                        size: 16,
                                        weight: 'bold'
                                    }
                                },
                                ticks: {
                                    font: {
                                        size: 14
                                    }
                                }
                            }
                        },
                        plugins: {
                            legend: {
                                labels: {
                                    font: {
                                        size: 16
                                    }
                                }
                            },
                            tooltip: {
                                titleFont: {
                                    size: 16
                                },
                                bodyFont: {
                                    size: 15
                                }
                            }
                        }
                    }
                });
                
                // 新增：各单位详细数据柱状图
                const detailsCtx = document.getElementById('detailsChart').getContext('2d');
                const detailsLabels = sortedData.map(item => item.体检医院);
                
                // 定义要显示的字段
                const fields = [
                    '一般检查', '老年评估', '生活方式', '物理检查项', 
                    '生化检查', '器械检查', '现存健康问题', '健康评价', 
                    '健康指导', '危险因素控制'
                ];
                
                // 定义颜色
                const colors = [
                    'rgba(93, 140, 174, 0.7)',
                    'rgba(127, 179, 213, 0.7)',
                    'rgba(247, 220, 111, 0.7)',
                    'rgba(88, 214, 141, 0.7)',
                    'rgba(243, 156, 18, 0.7)',
                    'rgba(231, 76, 60, 0.7)',
                    'rgba(52, 152, 219, 0.7)',
                    'rgba(155, 89, 182, 0.7)',
                    'rgba(149, 165, 166, 0.7)',
                    'rgba(241, 196, 15, 0.7)'
                ];
                
                // 创建数据集
                const datasets = fields.map((field, index) => {
                    return {
                        label: field,
                        data: sortedData.map(item => item[field]),
                        backgroundColor: colors[index],
                        borderColor: colors[index].replace('0.7', '1'),
                        borderWidth: 1
                    };
                });
                
                detailsChartInstance = new Chart(detailsCtx, {
                    type: 'bar',
                    data: {
                        labels: detailsLabels,
                        datasets: datasets
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '数量',
                                    font: {
                                        size: 16,
                                        weight: 'bold'
                                    }
                                },
                                ticks: {
                                    font: {
                                        size: 14
                                    }
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '体检医院',
                                    font: {
                                        size: 16,
                                        weight: 'bold'
                                    }
                                },
                                ticks: {
                                    font: {
                                        size: 14
                                    }
                                }
                            }
                        },
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    font: {
                                        size: 14
                                    }
                                }
                            },
                            tooltip: {
                                titleFont: {
                                    size: 16
                                },
                                bodyFont: {
                                    size: 15
                                }
                            }
                        }
                    }
                });
            } catch (error) {
                console.error('图表渲染失败:', error);
                // 显示错误提示
                document.getElementById('chartError1').style.display = 'block';
                document.getElementById('chartError2').style.display = 'block';
            }
        }

        // 数据筛选
        function filterData() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const regionFilter = document.getElementById('regionFilter').value;
            
            filteredData = originalData.filter(item => {
                const matchesSearch = item.体检医院.toLowerCase().includes(searchTerm);
                const matchesRegion = regionFilter ? item.体检医院 === regionFilter : true;
                return matchesSearch && matchesRegion;
            });
            
            // 重新排序
            sortTable(currentSort.column, currentSort.direction);
            
            // 更新UI
            updateStatistics();
            generateAnalysisReport();
            renderTable();
            renderCharts();
        }

        // 重置筛选
        function resetFilters() {
            document.getElementById('searchInput').value = '';
            document.getElementById('regionFilter').value = '';
            filterData();
        }

        // 表格排序
        function sortTable(column, direction = null) {
            // 确定排序方向
            if (currentSort.column === column) {
                currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            } else {
                currentSort.column = column;
                currentSort.direction = 'asc';
            }
            
            // 更新表头样式
            document.querySelectorAll('.sortable').forEach(header => {
                header.classList.remove('asc', 'desc');
                if (header.dataset.sort === currentSort.column) {
                    header.classList.add(currentSort.direction);
                }
            });
            
            // 如果是按region排序，使用原始顺序
            if (column === 'region') {
                // 创建region到原始索引的映射
                const regionOrderMap = {};
                originalData.forEach((item, index) => {
                    regionOrderMap[item.体检医院] = index;
                });
                
                // 按原始顺序排序
                filteredData.sort((a, b) => {
                    const indexA = regionOrderMap[a.体检医院];
                    const indexB = regionOrderMap[b.体检医院];
                    return currentSort.direction === 'asc' ? indexA - indexB : indexB - indexA;
                });
            } else {
                // 执行其他列的排序
                filteredData.sort((a, b) => {
                    let valueA = a[column === 'region' ? '体检医院' : getDataKey(column)];
                    let valueB = b[column === 'region' ? '体检医院' : getDataKey(column)];
                    
                    // 处理可能的空值
                    if (valueA === null || valueA === undefined) valueA = '';
                    if (valueB === null || valueB === undefined) valueB = '';
                    
                    // 数值排序
                    if (typeof valueA === 'number' && typeof valueB === 'number') {
                        return currentSort.direction === 'asc' ? valueA - valueB : valueB - valueA;
                    }
                    
                    // 字符串排序
                    valueA = String(valueA).toLowerCase();
                    valueB = String(valueB).toLowerCase();
                    
                    if (valueA < valueB) return currentSort.direction === 'asc' ? -1 : 1;
                    if (valueA > valueB) return currentSort.direction === 'asc' ? 1 : -1;
                    return 0;
                });
            }
            
            // 重新渲染表格
            renderTable();
            
            // 辅助函数：将表格列名映射到数据键名
            function getDataKey(column) {
                const mapping = {
                    'examCount': '体检总人次数',
                    'generalIssues': '一般检查',
                    'elderlyAssessment': '老年评估',
                    'lifestyleIssues': '生活方式',
                    'physicalExamIssues': '物理检查项',
                    'biochemicalExam': '生化检查',
                    'instrumentExam': '器械检查',
                    'existingHealthIssues': '现存健康问题',
                    'healthAssessment': '健康评价',
                    'healthGuidance': '健康指导',
                    'riskFactorControl': '危险因素控制'
                };
                return mapping[column] || column;
            }
        }
    </script>
</body>
</html>